package com.chb.javabasic.jpa;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class User2Service {
    @Autowired
    private User2Repository user2Respository;

    // 保存用户---更新+添加
    public User2 SaveUser2(User2 user) {
        return user2Respository.save(user);
    }

    //根据id查找用户
    @Cacheable(cacheNames = "user",key="#id")
    public Optional<User2> getUserByID(Long id) {
        log.info("getUserByID正在执行!");
        return user2Respository.findById(id);   // 不存在则返回null
    }

    // 根据用户名查询用户
    @Cacheable(cacheNames = "user",key="#username" )
    public Optional<User2> getUserByName(String username) {
        log.info("getUserByName正在执行!");
        return user2Respository.findByUsername(username);
    }

    // 查询所有用户
    public List<User2> getAllUsers() {
        return user2Respository.findAll();
    }

    // 删除用户
    //@CacheEnict注解使用该函数，再使用getUserByName，能否得到删除的数据
    @CacheEvict(cacheNames = "user",key="#id")
    public void deleteById(Long id) {
        user2Respository.deleteById(id);
    }

    @CacheEvict(cacheNames = "user",key="#username" )
    public void deleteByUsername(String username) {
        user2Respository.deleteByUsername(username);
    }

}
